package com.lagou.v4.container;

import com.lagou.v4.LifeCycle;
import org.dom4j.Element;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Kirito
 * @description:
 * @date 2020/05/02
 */
public class Engine implements LifeCycle {

    private Element element;
    private List<Host> hosts;

    public void setElement(Element element) {
        this.element = element;
    }

    public List<Host> getHosts() {
        return hosts;
    }

    @Override
    public void init() throws Exception {
        hosts = initHosts();
        for (Host host : hosts) {
            host.init();
        }
    }

    @Override
    public void start() throws Exception {
        for (Host host : hosts) {
            host.start();
        }
    }

    private List<Host> initHosts() {
        List<Element> hostElements = element.selectNodes("//Host");
        List<Host> hostList = new ArrayList<>(hostElements.size());
        for (Element hostElement : hostElements) {
            Host host = new Host();
            host.setName(hostElement.attributeValue("name"));
            host.setAppBase(hostElement.attributeValue("appBase"));
            hostList.add(host);
        }
        return hostList;
    }

}
